
 /*****************************************************************************
 * Copyright (c) 2004-2008 Javageo.com. All Rights Reserved.                 *
 *                                                                           *
 * This software is provided "AS IS," without a warranty of any kind.        *
 * You acknowledge that this software is not designed, licensed or intended  *
 * for use in the design, construction, operation or maintenance of any      *
 * nuclear facility.                                                         *
 * keep the world peace and green!                                           *
 *                                                                           *
 *@                                                                         **
 *@                                                                         **
 *@ JAVA       GoenSnap - Snap Image & Run by A program (wish use a webcam) **
 *@ Version#1.0                                                             **
 *@ By Goen-Ghin                                                            **
 *@ Date:  17-07-2008                                                       **
 *@ Pekanbaru Riau- Indonesia                                               **
 *****************************************************************************
 */

import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.net.URL;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.applet.Applet;
import java.applet.AudioClip;
import java.io.*;
import javax.swing.border.*;
import com.sun.image.codec.jpeg.*;
import com.sun.image.codec.*;
import java.awt.geom.*;
import javax.imageio.*;
import java.awt.print.*;
import javax.vecmath.Color3f;
import java.awt.image.*;
import java.net.*;
import java.util.Properties;
import java.util.Date;

/**
 * GUI for run GoenSnap
 */
// Internal classes

// Snap Image Class
public class GoenSnap {
  Toolkit toolkit;
  RunFile runfile;
  Timer timer;
  ReadConfig readconfig;
  static int MinuteAlert;
  static int alertMe;
  String my_currentDir;
  static int numberofFile = 0;   


  public GoenSnap() {
    toolkit = Toolkit.getDefaultToolkit();
    timer = new Timer();
    readconfig = new ReadConfig("goensnap.conf");
	my_currentDir = readconfig.getGoenSnapdir();

    MinuteAlert =  readconfig.getRemainderMinutes();  // execute the timer
    alertMe = readconfig.getRunMinutes();     // run snap image 
    timer.schedule(new SnapTimer(), 60, //initial delay
   //subsequent rate (every 1 menit for default )
       MinuteAlert * 60 * 1000);
  }
  
//Timer Task Class
  class SnapTimer extends TimerTask {
    int numWarningBeeps = 100;  // Set How many events 
    int numWarning = 0;         // Set Increment
    
    public void run() {
    	
      if (numWarningBeeps > 0) {
        
        // Sound file
      try
	   {   
	        

			runfile = new RunFile();
						
			//Snap an Image (JPG) is Ok but I Preferred PNG- Save image into directory then excute program to open/send the image
		    //GrapImage.write( GrapImage.take(), my_currentDir.toString()+File.separatorChar+"desktop"+numWarning+".jpg" );   
		   
		    GrapImage.writePNG( GrapImage.take(), my_currentDir.toString()+File.separatorChar+"desktop"+numWarning+".png" );   
		    
		    // Wait every alert me minute before run the program
		    //Send snap image file to a program 
		    runfile.goFile(alertMe * 60 * 1000,readconfig.getGoenRunwith(), my_currentDir.toString()+File.separatorChar+"desktop"+numWarning+".png");
		   		    
		    numWarningBeeps--;	
            numWarning ++;    	
		}
		catch (Exception e){}  
		
        
      } else {
      	
        
        numWarningBeeps = 100; //Back to Max
        //toolkit.beep(); //Bip bip
        //System.exit(0); //Stops the AWT thread (and everything else)
      }
    }
  }
  
  



static class RunFile {
	public static void goFile (int duration, String runcomfile, String file)
   {
   	try {
   		String addnoljam = "";
        String addnolmenit = "";
        String addnoldetik = "";
   		String s = null;
   		Runtime r = Runtime.getRuntime();
   		Properties p=System.getProperties();
   		Process ps = null;
        //excute program filename -- make sure the program can run..
 	    ps = r.exec(runcomfile+" "+ file); 
 	    
        numberofFile++;
        Date date = new Date();
        int nilai_jam = date.getHours();
        int nilai_menit = date.getMinutes();
        int nilai_detik = date.getSeconds();
        if (nilai_jam <= 9) {
          addnoljam = "0";
        }
        if (nilai_menit <= 9) {
          addnolmenit = "0";
        }
        if (nilai_detik <= 9) {
          addnoldetik = "0";
        }
        String jam = addnoljam + Integer.toString(nilai_jam);
        String menit = addnolmenit + Integer.toString(nilai_menit);
        String detik = addnoldetik + Integer.toString(nilai_detik);

   	    System.out.println("Process completed of " + numberofFile +" at Time: " + jam +":"+menit+":"+detik);

 	   Thread.sleep(duration);
 	    
   	}
   	catch (Exception e)  	 {
   		System.out.println("Error open file "+e); }
   		
   	}
   	
   }
// Snap Image Class
static class GrapImage {

//  Image File Types
	private static final int imageType = BufferedImage.TYPE_INT_RGB;	
	public static final String formatNameDefault = "jpg";
	
	private static final int imageTypePNG = BufferedImage.TYPE_4BYTE_ABGR;	
	public static final String formatNamePNG = "png";
	
	//Entire desktop
	public static BufferedImage take() throws AWTException, SecurityException {
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		Rectangle region = new Rectangle(0, 0, d.width, d.height);
		return take(region);
	}
	
	public static BufferedImage take(Rectangle region) throws IllegalArgumentException, AWTException, SecurityException {
		if (region == null) throw new IllegalArgumentException("region == null");
		
		return new Robot().createScreenCapture( region );
	}

    // Write file
	public static void write(BufferedImage image, String fileName) throws IllegalArgumentException, IOException {
		if (image == null) throw new IllegalArgumentException("image == null");
		if (fileName == null) throw new IllegalArgumentException("fileName == null");
		if (fileName.trim().length() == 0) throw new IllegalArgumentException("fileName is all whitespace");
		
		int index = fileName.lastIndexOf(".");
		String formatName = (index != -1) ? fileName.substring(index + 1) : formatNameDefault;
		
		File file = new File(fileName);
		
		write(image, formatName, file);
	}

	
 	public static void writePNG(BufferedImage image, String fileName) throws IllegalArgumentException, IOException {
		if (image == null) throw new IllegalArgumentException("image == null");
		if (fileName == null) throw new IllegalArgumentException("fileName == null");
		if (fileName.trim().length() == 0) throw new IllegalArgumentException("fileName is all whitespace");
		
		int index = fileName.lastIndexOf(".");
		String formatName = (index != -1) ? fileName.substring(index + 1) : formatNamePNG;
		
		File file = new File(fileName);
		
		write(image, formatNamePNG, file);
	}
	
	public static void write(BufferedImage image, String formatName, File file) throws IllegalArgumentException, IOException {
		if (image == null) throw new IllegalArgumentException("image == null");
		if (formatName == null) throw new IllegalArgumentException("formatName == null");
		if (formatName.trim().length() == 0) throw new IllegalArgumentException("formatName is all whitespace");
		if (file == null) throw new IllegalArgumentException("file == null");
		
		ImageIO.write(image, formatName, file);
	}

}
/*
 * A Class to read setting from goensnap.conf file 
*/

static class ReadConfig {
		static String s[] = new String[5] ;

	public ReadConfig(String sfile) {
		try {
  		FileReader fr = new FileReader(sfile); 
		BufferedReader br = new BufferedReader(fr);

		for (int i=0;i<5;i++) {
			s[i]=br.readLine();
		
		}
		}catch (IOException e) {
			
			System.out.println("Error while reading goensnap.conf file, due to " + e.getMessage());
			System.exit(1);
		}
		
	}
	public String getGoenSnapver(){ return s[0].substring(8);}
	public String getGoenSnapdir(){ return s[1].substring(8);}
	public int getRemainderMinutes(){ return Integer.valueOf(s[2].substring(12));}	
	public int getRunMinutes(){ return Integer.valueOf(s[3].substring(11));}
	public String getGoenRunwith(){ return s[4].substring(9);}

	
}  public static void main(String args[]) {
    System.out.println(" Save your Image and Run it with a Program !");

    new GoenSnap();
    System.out.println("Snap Image will done every "+MinuteAlert+" minutes.");
    System.out.println("and delay minutes of the program is "+alertMe);
    
  }

}
